package com.blkbox.dp.observer.impl;

import java.util.ArrayList;
import java.util.Iterator;

import com.blkbox.dp.observer.itf.IMaster;

public class NormalMaster implements IMaster {
    private boolean hook = false;
    private String message;
    private ArrayList<NormalReader> readerList = new ArrayList<NormalReader>();

    public void provideMessage(String message) {
        this.message = message;
        onMessgeCreated();
    }
    
    public void register(NormalReader normalReader){
        readerList.add(normalReader);
    }

    public void deRegister(NormalReader normalReader){
        readerList.remove(normalReader);
    }

    private void onMessgeCreated() {
        validateMessage();
        if (hook) {
            sendMessage();
        }
    }
    
    private void validateMessage() {
        hook = false;
        if (null != message && message.length() > 10) {
            hook = true;
        } else {
            hook = false;
        }
    }

    private void sendMessage() {
        Iterator<NormalReader> it = readerList.iterator();
        while (it.hasNext()) {
            NormalReader reader = it.next();
            if(reader.isPassiveRcv()){
                reader.receive(message);
            }
        }
    }
}
